#include "stdafx.h"
#include "TextureRender.h"
#include "texture.h"

CTextureRender::CTextureRender()
{
    SetUV( 0.0f, 0.0f, 1.0f, 1.0f );
    m_textureid = -1;
    m_vdata.vertexsize = sizeof(Vertex_RHW_TEX);
}

CTextureRender::~CTextureRender()
{
    
}

void CTextureRender::Render()
{
    TextureInfo *texinfo = CD3DManager::Instance().GetTextureInfo( m_textureid );
    CHECK_PTR_VOID( texinfo );
    IDirect3DDevice9 *pDevice = CD3DManager::Instance().GetDevice();
    if( m_sizex == -1 )
        m_sizex = int(texinfo->width * ( m_u2 - m_u1 ));
    if( m_sizey == -1 )
        m_sizey = int(texinfo->height * ( m_v2 - m_v1 ));
    float minx = (float)m_x;
    float miny = (float)m_y;
    float maxx = (float)(m_x+m_sizex-1);
    float maxy = (float)(m_y+m_sizey-1);
    Vertex_RHW_TEX ver[]=
    {
        {minx,miny,0.0f,1.0f,m_u1,m_v1},
        {maxx,miny,0.0f,1.0f,m_u2,m_v1},
        {maxx,maxy,0.0f,1.0f,m_u2,m_v2},

        {minx,miny,0.0f,1.0f,m_u1,m_v1},
        {maxx,maxy,0.0f,1.0f,m_u2,m_v2},
        {minx,maxy,0.0f,1.0f,m_u1,m_v2},
    };
    pDevice->SetTexture( 0, texinfo->texture );
    pDevice->SetFVF(Vertex_RHW_TEX::FVF);
    if( m_vdata.pData == NULL )
        pDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 2, ver, sizeof(Vertex_RHW_TEX) );
    else
        pDevice->DrawPrimitiveUP( D3DPT_TRIANGLELIST, m_vdata.count/3, m_vdata.pData, sizeof(Vertex_RHW_TEX) );
}

void CTextureRender::SetUV( float u1, float v1, float u2, float v2 )
{
    m_u1 = u1;
    m_v1 = v1;
    m_u2 = u2;
    m_v2 = v2;
}

void CTextureRender::LoadTexture( PCTSTR filename, int colorkey )
{
    m_textureid = CD3DManager::Instance().AddTexture( filename , colorkey);
}

void CTextureRender::SetTextureID( int id )
{
    m_textureid = id;
}

void CTextureRender::ClearVertexData()
{
    m_vdata.count = 0;
}

void CTextureRender::AddVertexData( void *data, uint32 count )
{
    uint32 datalen = count * m_vdata.vertexsize;
    uint32 restlen = m_vdata.RestBuffer();
    while( restlen < datalen )
    {
        m_vdata.Resize( datalen + m_vdata.bufferlen * 2 );
        restlen = m_vdata.RestBuffer();
    }
    memcpy( m_vdata.CurPosition(), data, datalen );
    m_vdata.count += count;
}

int CTextureRender::GetTextureID()
{
    return m_textureid;
}
